<script setup lang="ts">
import type { MessageBoxData } from 'element-plus'
import { ElButton } from 'element-plus'
import type { ComponentExposed } from 'vue-component-type-helpers'
import {
  ParticlesSettingPanel,
  SettingPanel,
} from './components'
import { editStateIdentity } from './'
import { alarmApi, indicatorApi } from '@/api'
import type {
  AlarmSaveOrUpdateWarningRuleParams,
  TableColumn,
} from '@/types'
// ------------------use------------------
// #region
const { form } = useKeepPageStore()
// !从指标页面跳转而来，当次页面重新刷新
form(['/indicator-tree-diagram'])
const { $confirm, $message } = useCurrentInstance()
const [isPanel, setIsPanel] = useState(true)
const { withLoading, spaceLoading, vLoading }
  = useDefineLoading()
const [alarmRule, setAlarmRule]
  = useState<AlarmSaveOrUpdateWarningRuleParams>([])
const [indicatorData, setIndicatorData] = useState<any[]>(
  [],
)
const [selectIndicator, setSelectIndicator] = useState({
  statisticalType: 0,
} as any)
const [selectNodeId, setSelectNodeId] = useState(0)
// 记录编辑状态
const [isEdit, setIsEdit] = useState(false)

const warningCategory = ref<string>('')

// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<any>[] = [
  {
    key: uuid(),
    label: '指标名称',
    prop: 'indicatorName',
  },
  {
    key: uuid(),
    label: '指标编码',
    prop: 'indicatorNumber',
  },
  {
    key: uuid(),
    label: '设备名称',
    prop: 'toolName',
  },
  {
    key: uuid(),
    label: '告警设置',
    width: 110,
    render({ row }) {
      return h(
        ElButton,
        {
          text: true,
          type: row.isWarning
            ? 'success'
            : 'primary',
        },
        {
          default: () =>
            row.isWarning ? '已设置' : '未设置',
        },
      )
    },
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const settingPanelRef
  = ref<ComponentExposed<typeof SettingPanel>>()
const particlesSettingPanelRef
  = ref<ComponentExposed<typeof ParticlesSettingPanel>>()
const viewTableRef = ref()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
function handleClickNode(p: any) {
  getIndicatorData(p.id)
  setSelectNodeId(p.id)
  reset()
  setSelectIndicator({
    statisticalType: 0,
  } as any)
  // setIsPanel(false);
}
async function getAlarmRule() {
  const { data: res } = await withLoading(
    alarmApi.selectWarningRuleByIndicatorId,
  )(selectIndicator.value.id)
  const params = JSON.parse(JSON.stringify(res))
  removeUnnecessaryParams(params)
  setAlarmRule(params)
  // console.log('规则：', alarmRule.value);
}
function tableRowClassName({ row }: any) {
  if (row.id === selectIndicator.value.id) {
    return 'table-highlight'
  }

  return ''
}
async function getIndicatorData(
  pointId: number = selectNodeId.value,
) {
  const { data: res } = await withLoading(
    indicatorApi.loadPointList,
    'indicator',
  )(pointId, 0)
  setIndicatorData(res)
}
async function handleRowClick(row: any) {
  const oldRow = selectIndicator.value
  if (isEdit.value) {
    const res: MessageBoxData = await $confirm(
      '数据可能未保存，确定切换？',
      '警告',
      {
        type: 'warning',
      },
    ).catch(e => e)
    if (res !== 'confirm') {
      setSelectIndicator(oldRow)
      return
    }
  }
  setSelectIndicator(row)
  if (row.indicatorDataStoreCoreList == null) {
    ElMessage.warning('该指标未设置存储周期')
  }
  await getAlarmRule()
  warningCategory.value = alarmRule.value[0]?.warningCategory ?? ''
  reset()
}
function reset() {
  settingPanelRef.value?.reset?.()
  particlesSettingPanelRef.value?.reset?.()
  setIsEdit(false)
}
async function save() {
  if (unref(warningCategory) === '') {
    $message.info('请先选择告警类别！')
    return false
  }
  let res = false
  if (selectIndicator.value.statisticalType === 2) {
    res = await settingPanelRef.value?.save?.()
  }
  else {
    res = await particlesSettingPanelRef.value?.save?.()
  }
  if (!res)
    return
  $message.success('数据保存成功！')
  getIndicatorData()
  await getAlarmRule()
  reset()
}
// #endregion
// 注入状态控制
provide(editStateIdentity, setIsEdit)
</script>

<template>
  <div class="padding-sm align-center overflow flex gap-sm container">
    <b-panel
      v-model:value="isPanel" :offset="10" class="flex-incompressible" :class="[
        {
          '-margin-left-sm': !isPanel,
        },
      ]" style="
        --panel-width: 240px;
      "
    >
      <ReadonlyPointTree @click-node="handleClickNode" />
    </b-panel>
    <div
      class="height-fill flex-incompressible padding-sm flex-direction panel panel-indicator-lists box-border flex gap-xs"
    >
      <div class="flex-incompressible panel-header">
        <h5 class="margin-0">
          告警指标列表
        </h5>
      </div>
      <b-mask
        content="数据为空，请切换点位！" :show="indicatorData.length === 0"
        class="width-fill flex-fillRemaining transparent-el-table overflow-auto"
      >
        <ViewTable
          ref="viewTableRef" :columns="columns" :loading="spaceLoading.indicator" :data="indicatorData"
          :show-toolbox="false" :row-class-name="tableRowClassName" class="height-fill" @row-click="handleRowClick"
        />
      </b-mask>
    </div>
    <div
      v-loading="{
        space: 'rule',
      }"
      class="panel height-fill flex-direction padding-sm width-auto panel-settings !flex-fillRemaining box-border flex overflow-auto"
    >
      <div class="panel-header align-center flex justify-between">
        <h5 class="margin-0">
          告警设置{{
            selectIndicator.indicatorName
              && `/${selectIndicator.indicatorName}${selectIndicator.indicatorCode ? `-${selectIndicator.indicatorCode}` : ''}`
          }}
        </h5>
        <ElButton :disabled="selectIndicator.statisticalType === 0" type="primary" @click="save">
          保存
        </ElButton>
      </div>
      <b-mask
        content="请先选择指标" :show="selectIndicator.statisticalType === 0"
        class="flex flex-1 flex-col overflow-auto"
      >
        <div class="mb-2 flex items-center">
          <span class="fs-14 flex-incompressible is-required" style="color: var(--el-text-color-secondary);">
            告警类别：
          </span>
          <DictionaryPicker v-model="warningCategory" :clearable="false" class="free ml-3px !w-240px" code="GAO_JING_LEI_BIE" />
        </div>
        <SettingPanel
          v-show="selectIndicator.statisticalType === 2" ref="settingPanelRef" :data="alarmRule"
          :indicator-info="selectIndicator" :warning-category="warningCategory"
        />

        <ParticlesSettingPanel
          v-show="selectIndicator.statisticalType === 1" ref="particlesSettingPanelRef"
          :particles-data="alarmRule" :indicator-info="selectIndicator"
          :warning-category="warningCategory"
        />
      </b-mask>
    </div>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------

.b-panel {
  --panel-width: 300px;
}

.panel-indicator-lists {
  --panel-width: 600px;

  @media screen and (max-width: 1560px) {
    --panel-width: 300px;
  }
}

.panel-settings {

  :deep(.setting-panel),
  :deep(.particles-setting-panel) {
    min-width: auto;
  }

  :deep(.setting-panel .el-input-number) {
    min-width: 80px;
  }
}
.is-required::before {
  content: '*';
  color: red;
}
//-------------样式穿透-------------
</style>
